<?php
/**
 * @author: zhangxingning
 * @contact: zhixiao476@gmail.com
 * @file: Helpers.php
 * @time: 2021/3/11 14:22
 * @desc: ${TEXT}
 */

function is_email($str) {
    return preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $str);
}

/**
 * 计算给定的hash数字的取余范围
 */
function hash_valueHex($hash_value, $hash_num = 8){
    $hash = substr(md5($hash_value),0, 2);
    $sv = "";
    for($i=0; $i<strlen($hash); $i++){
        $sv .= ord($hash[$i]);
    }
    return @base_convert(dechex($sv), 16, 2) % $hash_num;
}

// 微吼签名
function create_vh_sign($params){
    $params['auth_type'] = 2;
    $params['app_key'] = config('setting.vh_app_key');
    $params['signed_at'] = time();
    ksort($params);
    $_params = $params;

    array_walk($params,function(&$value,$key){
        $value = $key . $value;
    });
    $sign = md5(config('setting.vh_secret_key') . implode('',$params) . config('setting.vh_secret_key'));
    return ['sign' => $sign, 'params' => $_params];
}

// 微吼签名
function create_vh_sign2($params){
    /*$params['auth_type'] = 2;
    $params['app_key'] = config('setting.vh_app_key');
    $params['sign_type'] = 0;
    $params['signed_at'] = date("Y-m-d H:i:s");*/
    ksort($params);

    array_walk($params,function(&$value,$key){
        $value = $key . $value;
    });
    //echo config('setting.vh_secret_key') . implode('',$params) . config('setting.vh_secret_key');
    return md5(config('setting.vh_secret_key') . implode('',$params) . config('setting.vh_secret_key'));
}

function curl_post($url, $post_data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

    $output = curl_exec($ch);

    curl_close($ch);

    return json_decode($output, true);
}

function getRedis($db=0){
    $redis = new \Redis();
    $redis->connect(env('REDIS_HOST'), env('REDIS_PORT'), 60);
    if (env('REDIS_PASSWORD')) {
        $redis->auth(env('REDIS_PASSWORD'));
    }
    $redis->select($db);
    return $redis;
}

function apiSuccess($data, $message = '', $code = 0)
{

    return response()->json([
        'code'      => $code,
        'msg'       => $message,
        'body'      => $data,
    ], 200, [], JSON_UNESCAPED_UNICODE);
}

function apiError($message = '', $code = 400, $data = [])
{
    return response()->json([
        'code'      => $code,
        'msg'       => $message,
        'body'      => $data,
    ], 200,  [], JSON_UNESCAPED_UNICODE);
}

function downLoad($path, $name, $headers){
    return response()->download($path, $name, $headers);
}

/**
 * 识别图片url
 */
function getImgs($str){
    if (!$str) return false;
    preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$matches);
    if (!empty($matches[0])){
        return false;
    }else{
        return true;
    }

    $reg = '/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(jpg|gif|png|bmp|jpeg)/';
    preg_match_all($reg, $str, $matches);
    if (!empty($matches[0])){
        return false;
    }else{
        return true;
    }
}

/**
 * 将带域名的去掉
 */
function removeDomain($url, $domain_name){
    return replace($domain_name, '', $url);
}

function toArrayKeyForValue(array $data = array(), string $pk = 'id'): array{
    if (empty($data)) return [];
    $new_array = [];
    foreach ($data as $key => $val){
        $new_array[] = $val[$pk];
    }
    return $new_array;
}

function toArrayList(array $data, string $pk = 'id'): array{
    if (empty($data)) return [];
    $new_array = [];
    if (!isset($data[0][$pk])) return [];
    foreach ($data as $key => $val){
        $new_array[$val[$pk]] = $val;
    }
    return $new_array;
}

/*
 * 计算两个日期相差 年 月 日
 */
function DiffDate($date1,$date2){
    if(strtotime($date1) > strtotime($date2)){
        $ymd = $date2;
        $date2 = $date1;
        $date1 = $ymd;
    }
    [$y1,$m1,$d1] = explode('-',$date1);
    [$y2,$m2,$d2] = explode('-',$date2);
    $y = $m = $d = $_m = 0;
    $math = ($y2-$y1)*12+$m2-$m1;
    $y = round($math/12);
    $m = intval($math%12);
    $d = @(mktime(0,0,0,$m2,$d2,$y2) - mktime(0,0,0,$m2,$d1,$y2))/86400;
    if($d < 0){
        $m -= 1;
        $d += date('j',mktime(0,0,0,$m2,0,$y2));
    }
    $m < 0 && $y -= 1;
    return array($y,$m,$d);
}

if(!function_exists('stdClassToArray')){
    function stdClassToArray($staClass){
        if($staClass){
            return json_decode(json_encode($staClass), true);
        }else{
            return [];
        }
    }
}

function generate_code($length = 6) {
    $min = pow(10 , ($length - 1));
    $max = pow(10, $length) - 1;
    return rand($min, $max);
}

/**
 * 生成订单号
 */
function createOrderNumber()
{
    return date("YmdHis") . random_int(1000, 9999);
}
